package com.dd.cloud.gateway.exception;

/**
 *
 */

import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.vo.EnumResultVo;
import com.dd.cloud.common.vo.ExceptionResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Gateway 的全局异常处理器，将 Exception 翻译成 ExceptionResult + 对应的异常编号
 * 在功能上，和 核心 的 GlobalExceptionHandler 类是一致的
 * @Description: 网关统一异常处理
 * @Author: czg
 * @Date: 2023/12/13 10:45
 * @Version: 1.0.0
 */
@Component
@Order(-1) // 保证优先级高于默认的 Spring Cloud Gateway 的 ErrorWebExceptionHandler 实现
@Slf4j
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 已经 commit，则直接返回异常
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 转换成 CommonResult
        ExceptionResult result;
        if (ex instanceof ResponseStatusException) {
            result = responseStatusExceptionHandler(exchange, (ResponseStatusException) ex);
        } else if (ex instanceof ZekeException) {
            result = zkExceptionHandler(exchange, (ZekeException) ex);
        } else {
            result = defaultExceptionHandler(exchange, (Exception) ex);
        }

        // 返回给前端
        return WebFrameworkUtils.writeJSON(exchange, result);
    }

    /**
     * 处理 Spring Cloud Gateway 默认抛出的 ResponseStatusException 异常
     */
    private ExceptionResult responseStatusExceptionHandler(ServerWebExchange exchange,
                                                           ResponseStatusException ex) {
        ServerHttpRequest request = exchange.getRequest();
        log.error("[responseStatusExceptionHandler][uri({}/{}) 发生异常]", request.getURI(), request.getMethod(), ex);
        if (ex.getStatus().value() == GatewayExceptionEnum.SYS_GATEWAY_ERROR_NACOS.getCode()) {
            return new ExceptionResult(ex.getStatus().value(), null, " 请联系管理人员 : " + ex.getReason() + GatewayExceptionEnum
                    .SYS_GATEWAY_ERROR_NACOS.getMsg());
        }
        return new ExceptionResult(ex.getStatus().value(), null, ex.getReason());
    }

    /**
     * 处理已知系统异常
     */
    public ExceptionResult zkExceptionHandler(ServerWebExchange exchange,
                                              ZekeException e) {
        if (e.getEnumInterface() != null && e.getEnumInterface().getMessage() != null) {
            EnumResultVo vo = e.getEnumInterface().getMessage();
            return new ExceptionResult(vo);
        }
        return new ExceptionResult(e.getStatus(), null, e.getMsg());
    }

    /**
     * 处理未知系统异常
     */
    public ExceptionResult defaultExceptionHandler(ServerWebExchange exchange,
                                                   Exception ex) {
        log.error("网关 发生异常, {}", ex);
        ex.printStackTrace();
        return new ExceptionResult(500, null, "网关异常, 请稍后重试");
    }

}

